package com.flowable.controller;

import com.flowable.entity.LeaveRequest;
import com.flowable.service.LeaveService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/leave")
public class LeaveController {

    @Autowired
    private LeaveService leaveService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    /**
     * 首页
     */
    @GetMapping("/")
    public String index() {
        return "index";
    }

    /**
     * 请假申请页面
     */
    @GetMapping("/apply")
    public String applyPage() {
        return "apply";
    }

    /**
     * 提交请假申请
     */
    @PostMapping("/submit")
    @ResponseBody
    public Map<String, Object> submitLeave(@RequestBody Map<String, Object> request) {
        log.info("提交请假申请，请求参数：{}", request);
        try {
            String applicant = (String) request.get("applicant");
            String reason = (String) request.get("reason");
            LocalDate startDate = LocalDate.parse((String) request.get("startDate"));
            LocalDate endDate = LocalDate.parse((String) request.get("endDate"));

            int days = (int) ChronoUnit.DAYS.between(startDate, endDate) + 1;

            LeaveRequest leaveRequest = new LeaveRequest(applicant, reason, startDate, endDate, days);
            String processInstanceId = leaveService.submitLeaveRequest(leaveRequest);

            log.info("请假申请提交成功,processInstanceId:{}", processInstanceId);

            return Map.of(
                    "success", true,
                    "message", "请假申请提交成功",
                    "processInstanceId", processInstanceId
            );
        } catch (Exception e) {
            return Map.of(
                    "success", false,
                    "message", "提交失败: " + e.getMessage()
            );
        }
    }

    /**
     * 领导审批页面
     */
    @GetMapping("/manager")
    public String managerPage(Model model) {

        List<Task> tasks = leaveService.getManagerTasks();
        model.addAttribute("tasks", tasks);
        return "manager";
    }

    /**
     * 老板审批页面
     */
    @GetMapping("/boss")
    public String bossPage(Model model) {
        List<Task> tasks = leaveService.getBossTasks();
        model.addAttribute("tasks", tasks);
        return "boss";
    }


    /**
     * 获取任务详情
     */
    @GetMapping("/task/{taskId}")
    @ResponseBody
    public Map<String, Object> getTaskDetails(@PathVariable String taskId) {
        return leaveService.getTaskDetails(taskId);
    }

    /**
     * 领导审批处理
     */
    @PostMapping("/manager/approve")
    @ResponseBody
    public Map<String, Object> managerApprove(@RequestBody Map<String, Object> request) {
        try {
            log.info("领导审批处理,request:{}", request);
            String taskId = (String) request.get("taskId");
            String approvalResult = (String) request.get("approvalResult");
            String comment = (String) request.get("comment");

            leaveService.managerApproval(taskId, approvalResult, comment);

            return Map.of(
                    "success", true,
                    "message", "审批完成"
            );
        } catch (Exception e) {
            log.error("领导审批处理失败，原因：{}",e.getMessage());
            return Map.of(
                    "success", false,
                    "message", "审批失败: " + e.getMessage()
            );
        }
    }

    /**
     * 老板审批处理
     */
    @PostMapping("/boss/approve")
    @ResponseBody
    public Map<String, Object> bossApprove(@RequestBody Map<String, Object> request) {
        try {
            String taskId = (String) request.get("taskId");
            String approvalResult = (String) request.get("approvalResult");
            String comment = (String) request.get("comment");

            leaveService.bossApproval(taskId, approvalResult, comment);

            return Map.of(
                    "success", true,
                    "message", "审批完成"
            );
        } catch (Exception e) {
            return Map.of(
                    "success", false,
                    "message", "审批失败: " + e.getMessage()
            );
        }
    }

    /**
     * 流程监控页面
     */
    @GetMapping("/monitor")
    public String monitorPage(Model model) {
        List<ProcessInstance> processes = leaveService.getRunningProcesses();
        model.addAttribute("processes", processes);
        return "monitor";
    }



    /**
     * 查询流程历史
     */
    @GetMapping("/history/{processInstanceId}")
    @ResponseBody
    public List<String> getProcessHistory(@PathVariable String processInstanceId) {

        return leaveService.getProcessHistory(processInstanceId);
    }
}